<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-24 5:40 下午
 *
 */

namespace app\admin\controller;


use app\admin\service\UploadFileService;
use app\common\controller\AdminBaseController;
use app\common\energyApi\Energy;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\Feedback as FeedbackModel;
use app\common\model\tang\WatchLog;
use app\common\model\tang\WatchMaintain;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Log;

class Balance  extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new BalanceLog();
    }

    public function index()
    {
        if (IS_AJAX){
            return $this->model->getAdminPageData($this->param, 'id desc');
        }
        $merchant_list =getMerchant();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }
    /**
     * 导入
     */
    public function import()
    {
        header("content-type:text/html;charset=utf-8");
        //上传excel文件
        $res = UploadFileService::instance()->setUploadPath('store/excel')->image('file');
        if ($res) {
            //获取上传到后台的文件名
            $fileName = $res['name'];
            //获取文件路径
            $filePath = app()->getRootPath() . 'public' . $res['thumb_path'];
            //获取文件后缀
            $suffix = $res['ext'];
            // 有Xls和Xlsx格式两种
            $reader = IOFactory::createReader('Xlsx');
        } else {
            return json(['status' => '1', 'message' => '文件过大或格式不正确导致上传失败-_-!']);
        }
//        $spreadsheet = $reader->load($filePath);

        //载入excel文件
//        $excel = $reader->load($filePath);
        $excel = IOFactory::load($filePath);
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        $merchantModel = new \app\common\model\tang\Merchant();
        $import_data = []; //数组形式获取表格数据
        try {
            for ($i = 2; $i <= $row_num; $i++) {
                $data = [];
                $data['company'] = $excel->getActiveSheet()->getCell("A" . $i)->getValue();
                $data['code'] = $excel->getActiveSheet()->getCell("B" . $i)->getValue();
                $merchant_id = $merchantModel->where('code',$data['code'])->value('id');
                if(empty($merchant_id)){
                    throw new Exception('第'.$i.'行'. $data['code'].'未录入商户信息');
                }
                $merchantList[] =$merchant_id;
                $data['mobile'] = $excel->getActiveSheet()->getCell("D" . $i)->getValue();
                $data['charge_time'] =$excel->getActiveSheet()->getCell("E" . $i)->getValue();
                $data['amount'] = $excel->getActiveSheet()->getCell("F" . $i)->getValue();
                $data['rate'] = $excel->getActiveSheet()->getCell("G" . $i)->getValue();
                $data['amount'] = $data['amount']*100;
                $data['charge_time'] = strtotime($data['charge_time']);
                $data['is_top_up'] = 1;
                $data['merchant_id'] = $merchant_id;
                $data['edit'] = 1;
                if($data['rate']=='线上充值'){
                    $data['type'] = 1;
                }else{
                    $data['type'] = 2;
                }
                $import_data[] = $data;
            }
            (new BalanceLog())->saveAll($import_data);
            $Energy = new Energy();
            if(!empty($merchantList)){
                foreach ($merchantList as $k=>$v){
                    upMerchantAuto($v);
                }
                foreach ($merchantList as $kk=>$vv){
                    $merchantInfo = (new \app\common\model\tang\Merchant())->where('id',$vv)->value('balance');
                    if($merchantInfo>-1){
                        $watch_list = (new WatchMaintain())->where('merchant_id',$vv)->where('type',1)->select();
                        if(!empty($wechat_info)){
                            $watch_list = $watch_list->toArray();
                            Log::info('转账商户电表列表:'.json_encode($watch_list));
                            $watch= new WatchLog();
                            foreach ($watch_list as $ks=>$vs){
                                $watch_data = [];
                                $watch_data = [
                                    "pointId" => $vs['pointId'],
                                    "operType" => 2 //1 拉闸2 合闸
                                ];
                                Log::info('转账合闸请求数据:'.json_encode($watch_data));
                                // 查询月电费接口
                                $port_data = $Energy->universalfunction('remote_disconnect', $watch_data);
                                if(isset($port_data)){
                                    $watch->pointId = $watch_data['pointId'];
                                    $watch->operType = $watch_data['operType'];
                                    $watch->return_info = json_encode($port_data);
                                    $watch->create_time = time();
                                    $watch->save();
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            return self::ajaxResult([], 0, 1, $e->getMessage());
        }

        return self::ajaxResult([], 0, 1, '导入成功');
    }

    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:添加编辑
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            return $this->model->doAll($data);
        }
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //获取菜单列表
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }
    public function export()
    {
        $title = ['公司名称', '海鼎合同号', '华立户号', '手机号', '充值时间','金额',  '线上充值/转账'];
        return export_excel('充值记录_' . date('Y-m-d'), $title, []);
    }
    public function del()
    {
        $ids = $this->request->post("ids");
        $info = $this->model->where('id',$ids)->value('merchant_id');
        $result = $this->model->delById($ids);
        if($result){
            upMerchantAuto($info);
        }
        return self::ajaxResult([], 0, 1, '删除成功');
    }
}